<template>
  <view class="container">
    <!-- 订单状态 -->
    <view class="status-section">
      <view class="status-header" v-if="orderDetail">
        <text class="status-text">{{ getStatusText(orderDetail) }}</text>
        <text class="status-desc">{{ getStatusDescription(orderDetail) }}</text>
        <!-- 倒计时显示 -->
        <view class="countdown-wrapper" v-if="orderDetail.orderStatus === 'pending'">
          <template v-if="countdownTime">
            <text class="countdown-label">支付倒计时：</text>
            <text class="countdown-time">{{ countdownTime }}</text>
          </template>
          <template v-else>
            <text class="countdown-expired">订单已过期</text>
          </template>
        </view>
      </view>
      <image v-if="orderDetail" class="status-image" :src="getStatusImage(orderDetail)" mode="aspectFit"/>
    </view>

    <!-- 收货地址 -->
    <view class="info-card address-card">
      <view class="card-header">
        <image src="/static/address/location.png" class="header-icon"/>
        <text class="header-title">收货地址</text>
      </view>
      <view class="address-info" v-if="orderDetail">
        <view class="user-info">
          <text class="name">{{ orderDetail.address?.userName }}</text>
          <text class="phone">{{ orderDetail.address?.phone }}</text>
        </view>
        <text class="address-detail">{{ orderDetail.address?.addressName }}</text>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="info-card">
      <view class="card-header">
        <image src="/static/order/package.png" class="header-icon"/>
        <text class="header-title">商品信息</text>
      </view>
      <view class="product-info" v-if="orderDetail">
        <image 
          :src="orderDetail.productSKUVO?.image || '/static/https://fsp-1326500412.cos.ap-chengdu.myqcloud.com/default.png'"
          mode="aspectFill" 
          class="product-image"
        />
        <view class="product-detail">
          <text class="product-name">{{ orderDetail.product?.name }}</text>
          <text class="sku-info">{{ orderDetail.productSKUVO?.quantity }}</text>
          <view class="price-quantity">
            <text class="price">¥{{ orderDetail.productSKUVO?.price?.toFixed(2) }}</text>
            <text class="quantity">x{{ orderDetail.quantity }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="info-card">
      <view class="card-header">
        <image src="/static/profile/wodedingdan.png" class="header-icon"/>
        <text class="header-title">订单信息</text>
      </view>
      <view class="order-info" v-if="orderDetail">
        <view class="info-item">
          <text class="label">订单编号</text>
          <view class="value-copy">
            <text class="value">{{ orderDetail.id }}</text>
            <button class="copy-btn" @tap="copyOrderId">复制</button>
          </view>
        </view>
        <view class="info-item">
          <text class="label">创建时间</text>
          <text class="value">{{ formatTime(orderDetail.createTime) }}</text>
        </view>
        <view class="info-item" v-if="orderDetail.paymentTime">
          <text class="label">支付时间</text>
          <text class="value">{{ formatTime(orderDetail.paymentTime) }}</text>
        </view>
      </view>
    </view>

    <!-- 金额明细 -->
    <view class="info-card">
      <view class="card-header">
        <image src="/static/order/wallet.png" class="header-icon"/>
        <text class="header-title">金额明细</text>
      </view>
      <view class="amount-info" v-if="orderDetail">
        <view class="amount-item">
          <text class="label">商品原价</text>
          <text class="value original-price">¥{{ orderDetail.originalPrice?.toFixed(2) }}</text>
        </view>
        <!-- 优惠券折扣 -->
        <view class="amount-item discount-row" v-if="orderDetail.discountAmount && orderDetail.discountAmount > 0">
          <text class="label">优惠券折扣</text>
          <text class="value discount">-¥{{ orderDetail.discountAmount?.toFixed(2) }}</text>
        </view>
        <view class="amount-item">
          <text class="label">运费</text>
          <text class="value">¥0.00</text>
        </view>
        <view class="amount-item total">
          <text class="label">实付金额</text>
          <text class="value highlight">¥{{ orderDetail.totalPrice?.toFixed(2) }}</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="footer">
      <view class="action-buttons" v-if="orderDetail">
        <!-- 待支付状态 -->
        <template v-if="orderDetail.orderStatus === 'pending'">
          <button class="action-btn secondary" @tap="cancelOrder">取消订单</button>
          <button class="action-btn primary" @tap="payOrder">立即支付</button>
        </template>
        
        <!-- 待收货状态 -->
        <template v-if="orderDetail.orderStatus === 'shipped'">
          <button class="action-btn primary" @tap="confirmReceive">确认收货</button>
        </template>
        
        <!-- 已完成状态 -->
        <template v-if="orderDetail.orderStatus === 'completed'">
          <button class="action-btn secondary" @tap="applyRefund">申请退款</button>
          <button class="action-btn primary" @tap="buyAgain">再次购买</button>
        </template>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import type { API } from '@/backend/typings.d';
import {cancelOrderUsingPost, getOrderVoByIdUsingGet, updateOrderUsingPost, payOrderUsingPost, confirmReceiptUsingPost} from '@/backend';
import { createCountdown, clearCountdown, calculateTimeLeft } from '@/utils/countdown';
import { request } from '@/utils/requestWrapper';

const orderDetail = ref<API.OrderVO>();
const countdownTime = ref<string>('');
let countdownTimer = 0; // 保存定时器ID

// 获取订单详情
const fetchOrderDetail = async (id: string) => {
  try {
    // 直接传递字符串ID
    const res = await getOrderVoByIdUsingGet({
      id: id
    });
    
    if (res.code === 0 && res.data) {
      orderDetail.value = res.data;
      
      // 设置倒计时
      setupCountdown();
    } else {
      uni.showToast({
        title: res.message || '获取订单详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取订单详情失败：', error);
    uni.showToast({
      title: '获取订单详情失败',
      icon: 'none'
    });
  }
};

// 设置倒计时
const setupCountdown = () => {
  // 清除现有定时器
  if (countdownTimer) {
    clearCountdown(countdownTimer);
    countdownTimer = 0;
  }
  
  // 如果订单是待支付状态，且有创建时间，则启动倒计时
  if (orderDetail.value?.orderStatus === 'pending' && orderDetail.value?.createTime) {
    const timeLeft = calculateTimeLeft(orderDetail.value.createTime, 30);
    
    // 如果已过期，将 countdownTime 设为空字符串，显示过期状态
    if (!timeLeft) {
      countdownTime.value = '';
      return;
    }
    
    countdownTimer = createCountdown(
      orderDetail.value.createTime,
      30, // 30分钟后过期
      (timeString) => {
        countdownTime.value = timeString;
      },
      () => {
        // 倒计时结束，显示过期状态
        countdownTime.value = '';
        
        // 延迟1秒后刷新订单详情，查看后端是否已更新订单状态
        setTimeout(() => {
          if (orderDetail.value?.id) {
            fetchOrderDetail(orderDetail.value.id.toString());
          }
        }, 1000);
      }
    );
  } else {
    countdownTime.value = '';
  }
};

// 获取状态文本
const getStatusText = (order?: API.OrderVO) => {
  if (!order) return '';
  switch (order.orderStatus) {
    case 'pending': return '待支付';
    case 'paid': return '待发货';
    case 'shipped': return '待收货';
    case 'completed': return '已完成';
    case 'cancelled': return '已取消';
    default: return '未知状态';
  }
};

// 获取状态描述
const getStatusDescription = (order?: API.OrderVO) => {
  if (!order) return '';
  switch (order.orderStatus) {
    case 'pending': return '请在30分钟内完成支付';
    case 'paid': return '商家正在处理您的订单';
    case 'shipped': return '商品正在配送中';
    case 'completed': return '交易已完成';
    case 'cancelled': return '订单已取消';
    default: return '';
  }
};

// 获取状态图片
const getStatusImage = (order?: API.OrderVO) => {
  if (!order) return '';
  switch (order.orderStatus) {
    case 'pending': return '/static/order/waiting-payment.png';
    case 'paid': return '/static/order/waiting-delivery.png';
    case 'shipped': return '/static/order/in-delivery.png';
    case 'completed': return '/static/order/completed.png';
    case 'cancelled': return '/static/order/cancelled.png';
    default: return '';
  }
};

// 格式化时间
const formatTime = (time?: string) => {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 复制订单号
const copyOrderId = () => {
  if (orderDetail.value?.id) {
    uni.setClipboardData({
      data: orderDetail.value.id.toString(),
      success: () => {
        uni.showToast({
          title: '复制成功',
          icon: 'success'
        });
      }
    });
  }
};

// 订单操作函数
const payOrder = async () => {
  if (!orderDetail.value?.id) return;
  
  try {
    const result = await new Promise<{confirm: boolean, cancel?: boolean}>((resolve) => {
      uni.showModal({
        title: '确认支付',
        content: `确定要支付￥${orderDetail.value?.totalPrice?.toFixed(2)}吗？`,
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => resolve(res),
        fail: () => resolve({confirm: false})
      });
    });

    if (!result.confirm) return;

    const res = await payOrderUsingPost(orderDetail.value.id);
    if (res.code === 0) {
      uni.showToast({
        title: '支付成功',
        icon: 'success'
      });
      await fetchOrderDetail(orderDetail.value.id.toString());
    } else {
      uni.showToast({
        title: res.message || '支付失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('支付失败：', error);
    uni.showToast({
      title: '支付失败',
      icon: 'none'
    });
  }
};

const cancelOrder = async () => {
  if (!orderDetail.value?.id) return;
  
  try {
    const result = await new Promise<{confirm: boolean, cancel?: boolean}>((resolve) => {
      uni.showModal({
        title: '取消订单',
        content: '确定要取消该订单吗？',
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => resolve(res),
        fail: () => resolve({confirm: false})
      });
    });

    if (!result.confirm) return;

    const res = await cancelOrderUsingPost(orderDetail.value.id);
    if (res.code === 0) {
      uni.showToast({
        title: '取消订单成功',
        icon: 'success'
      });
      await fetchOrderDetail(orderDetail.value.id.toString());
    } else {
      uni.showToast({
        title: res.message || '取消订单失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('取消订单失败：', error);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

const confirmReceive = async () => {
  if (!orderDetail.value?.id) return;
  
  try {
    const result = await new Promise<{confirm: boolean, cancel?: boolean}>((resolve) => {
      uni.showModal({
        title: '确认收货',
        content: '确认已收到商品吗？确认后无法撤销',
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => resolve(res),
        fail: () => resolve({confirm: false})
      });
    });

    if (!result.confirm) return;

    const res = await confirmReceiptUsingPost(orderDetail.value.id);
    if (res.code === 0) {
      uni.showToast({
        title: '确认收货成功',
        icon: 'success'
      });
      await fetchOrderDetail(orderDetail.value.id.toString());
    } else {
      uni.showToast({
        title: res.message || '确认收货失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('确认收货失败：', error);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

const applyRefund = () => {
  if (!orderDetail.value?.id) return;
  
  uni.navigateTo({
    url: `/pages/afterSales/apply?order=${encodeURIComponent(JSON.stringify(orderDetail.value))}`
  });
};

const buyAgain = () => {
  if (!orderDetail.value?.productSKUVO?.id || !orderDetail.value?.product?.id) return;
  
  const productSKU = orderDetail.value.productSKUVO;
  const product = orderDetail.value.product;
  
  // 构建商品SKU信息
  const orderInfo = {
    productSKU: productSKU,
    quantity: 1 // 默认购买数量为1
  };
  
  // 跳转到确认订单页面
  uni.navigateTo({
    url: `/pages/order/confirm?info=${encodeURIComponent(JSON.stringify(orderInfo))}`
  });
};

// 接收页面参数
onLoad((options: any) => {
  if (options.idStr) {
    // 使用字符串格式的ID获取订单详情
    fetchOrderDetail(decodeURIComponent(options.idStr));
  } else if (options.id) {
    // 兼容旧版本的处理方式
    fetchOrderDetail(options.id);
  }
});

// 在组件卸载时清除定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearCountdown(countdownTimer);
  }
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

.status-section {
  background: linear-gradient(135deg, #ff9800, #ff5722);
  padding: 40rpx 32rpx;
  color: #fff;
  position: relative;
  overflow: hidden;
}

.status-header {
  position: relative;
  z-index: 1;
}

.status-text {
  font-size: 40rpx;
  font-weight: 600;
  margin-bottom: 12rpx;
  display: block;
}

.status-desc {
  font-size: 26rpx;
  opacity: 0.9;
}

.status-image {
  position: absolute;
  right: 32rpx;
  bottom: 0;
  width: 200rpx;
  height: 200rpx;
  opacity: 0.2;
}

.info-card {
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 24rpx;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.header-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 12rpx;
}

.header-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
}

.address-info {
  padding: 16rpx 0;
}

.user-info {
  margin-bottom: 12rpx;
}

.name {
  font-size: 28rpx;
  font-weight: 500;
  margin-right: 24rpx;
}

.phone {
  font-size: 28rpx;
  color: #666;
}

.address-detail {
  font-size: 26rpx;
  color: #666;
  line-height: 1.4;
}

.product-info {
  display: flex;
  gap: 20rpx;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  background: #f5f5f5;
}

.product-detail {
  flex: 1;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.sku-info {
  font-size: 24rpx;
  color: #999;
}

.price-quantity {
  margin-top: 16rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 32rpx;
  color: #ff5722;
  font-weight: 600;
}

.quantity {
  font-size: 26rpx;
  color: #666;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.label {
  font-size: 26rpx;
  color: #666;
}

.value {
  font-size: 26rpx;
  color: #333;
}

.value-copy {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.copy-btn {
  font-size: 24rpx;
  color: #666;
  background: #f5f5f5;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.original-price {
  text-decoration: line-through;
  color: #999;
}

.discount-row {
  background-color: rgba(255, 87, 34, 0.05);
  padding: 8rpx;
  border-radius: 8rpx;
  margin: 12rpx 0;
}

.discount {
  color: #ff5722;
  font-weight: 500;
}

.amount-item.total {
  margin-top: 16rpx;
  padding-top: 16rpx;
  border-top: 2rpx solid #f5f5f5;
}

.highlight {
  color: #ff5722;
  font-size: 32rpx;
  font-weight: 600;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.action-btn {
  min-width: 180rpx;
  height: 72rpx;
  font-size: 28rpx;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn.primary {
  background: linear-gradient(135deg, #ff9800, #ff5722);
  color: #fff;
}

.action-btn.secondary {
  background: #fff;
  color: #666;
  border: 2rpx solid #ddd;
}

.countdown-wrapper {
  display: flex;
  align-items: center;
  margin-top: 16rpx;
  background-color: rgba(255, 255, 255, 0.15);
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  width: fit-content;
}

.countdown-label {
  font-size: 24rpx;
  color: #fff;
  margin-right: 6rpx;
}

.countdown-time {
  font-size: 26rpx;
  font-weight: bold;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.2);
  padding: 2rpx 8rpx;
  border-radius: 6rpx;
  letter-spacing: 2rpx;
}

.countdown-expired {
  color: #ff5722;
  font-size: 26rpx;
  font-weight: bold;
}
</style> 